package com.enqualcomm.kids.mvp.terminalbill;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.enqualcomm.kids.component.MySqlitOpenHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Sunzhigang on 2015/11/3.
 */
public class BillDBManager {
    private SQLiteDatabase mdb;
    private String userid;

    public BillDBManager(Context context,String userid) {
        this.userid = userid;
        mdb = MySqlitOpenHelper.getInstance(context).getWritableDatabase();
    }

    /**
     *将短信消息json数据发到数据库中
     * @param terminalid
     * @param smsList
     * @return
     */
    public void insertBillSMS(String terminalid, List<String> smsList) {
        mdb.beginTransaction();
        try {
            for (String message : smsList) {
                mdb.execSQL("INSERT INTO billsms VALUES(null, ?, ?, ?)", new Object[]{userid, terminalid,message});
            }
            mdb.setTransactionSuccessful();
        } finally {
            mdb.endTransaction();
        }
    }

    /**
     *查询数据库中的手表话费流量信息
     * @param terminalid
     * @return
     */
    public List<String> queryBillSMS(String terminalid){
        List<String> smsList=new ArrayList<>();
        Cursor cursor = mdb.rawQuery("SELECT * FROM billsms WHERE terminalid =? order by _id asc", new String[]{terminalid});
        while(cursor.moveToNext()){
            String sms = cursor.getString(cursor.getColumnIndex("smsjson"));
            smsList.add(sms);
        }
        cursor.close();
        return smsList;
    }

    public void deleteSMSFromDB(String terminalid){
        mdb.delete("billsms","terminalid = ?",new String[]{terminalid});
    }

    public void deleteSMSFromDB(String terminalid,String smsjson){
        mdb.delete("billsms","terminalid = ? and smsjson = ?",new String[]{terminalid,smsjson});
    }
}
